package com.tbdp.lsmp.job;

import com.google.common.base.Preconditions;

import com.tbdp.lsmp.common.Configuration;
import com.tbdp.lsmp.common.Constants;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * 定时任务入口
 * @author xbkaishui
 * @version $Id: JobScheduler.java, v 0.1 2017-11-05 下午1:56 xbkaishui Exp $$
 */
public class JobScheduler {

    private static Logger logger = LoggerFactory.getLogger(JobScheduler.class);

    private Scheduler sched;

    /**
     * 初始化定时器
     */
    public void init() {
        logger.info(" init scheduler ...");
        String schedule = Configuration.getInstance().getProperty(Constants.SCHEDULE_PERIOD);
        Preconditions.checkNotNull(schedule, "调度周期没有设置");

        try {
            SchedulerFactory sf = new StdSchedulerFactory();
            sched = sf.getScheduler();

            //init job
            JobDetail job = newJob(SelectStockJob.class).withIdentity("job1", "SelectStock").build();

            CronTrigger trigger = newTrigger().withIdentity("trigger1", "SelectStock").withSchedule(cronSchedule(schedule))
                    .build();
            Date ft = sched.scheduleJob(job, trigger);

            logger.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
                    + trigger.getCronExpression());

        } catch (Exception e) {
            logger.error("init scheduler failed", e);
            System.exit(-1);
        }

    }

    /**
     * 启动定时器
     */
    public void start() {
        logger.info(" start scheduler ...");
        try {
            sched.start();
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void stop() {

        logger.info(" stop scheduler ...");

        logger.info("------- Shutting Down ---------------------");

        try {
            sched.shutdown(true);
            logger.info("------- Shutdown Complete -----------------");
            SchedulerMetaData metaData = sched.getMetaData();
            logger.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
        } catch (SchedulerException e) {
            logger.error(e.getMessage(), e);
        }

    }
}
